#include "network_server.h"

namespace engine
{
	bool NetworkServer::start(const char* host, uint16 port, uint32 maxConnections)
	{
		if (maxConnections > 0)
		{
			return mLibEvent.start(host, port, maxConnections);
		}

		return false;
	}

	void NetworkServer::stop()
	{
		mLibEvent.stop();
	}

	void NetworkServer::bindData(void* net, void* data)
	{
		Connection* conn = (Connection*)net;

		mLibEvent.bindData(conn, data);
	}

	void* NetworkServer::bindData(void* net)
	{
		Connection* conn = (Connection*)net;

		return mLibEvent.bindData(conn);
	}

	void NetworkServer::addListener(NetworkServerListener* listener)
	{
		mListeners.push_back(listener);
	}

	void NetworkServer::removeListener(NetworkServerListener* listener)
	{
		mListeners.remove(listener);
	}

	NetworkStream& NetworkServer::beginStream()
	{
		mSendStream.clear();

		return mSendStream;
	}

	void NetworkServer::sendStream(const NetworkStream& stream, void* net)
	{
		Connection* conn = (Connection*)net;

		mLibEvent.send(stream.getData(), stream.getLength(), conn);
	}

	void NetworkServer::handleMessages()
	{
		Message* pmsg = NULL;

		while ((pmsg = mLibEvent.lockMessage()))
		{
			Message msg = *pmsg;

			mLibEvent.unlockMessage();

			switch (msg.type)
			{
			case Message::ConnectionAccepted:
				{
					ListenerList::iterator it = mListeners.begin();

					for (; it != mListeners.end(); ++it)
					{
						(*it)->onConnected(msg.conn);
					}
				}
				break;

			case Message::ConnectionBreak:
				{
					ListenerList::iterator it = mListeners.begin();

					for (; it != mListeners.end(); ++it)
					{
						(*it)->onDisconnected(msg.conn);
					}

					mLibEvent.freeConnection(msg.conn);
				}
				break;

			case Message::ConnectionMessage:
				{
					mRecvStream.setData(msg.buff, msg.size);

					ListenerList::iterator it = mListeners.begin();

					for (; it != mListeners.end(); ++it)
					{
						mRecvStream.setPosition(0);

						(*it)->onMessage(msg.conn, mRecvStream);
					}

					mLibEvent.freeBuffer(msg.buff, msg.size);
				}
				break;

			default:
				assert(false);
			}
		}
	}

}
